package com.wlz.reconnect;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * @author wlz
 * @date 2022-07-09  5:14 下午
 */
@Slf4j
public class ReconnectNettyClient{

    private String host;
    private int port;
    private Bootstrap bootstrap;
    private EventLoopGroup group;

    public ReconnectNettyClient(String host, int port) {
        this.host = host;
        this.port = port;
        init();
    }

    public static void main(String[] args) throws Exception{
        ReconnectNettyClient reconnectNettyClient = new ReconnectNettyClient("127.0.0.1", 9000);
        reconnectNettyClient.connect();
    }


    void init() {
        group = new NioEventLoopGroup();
        try {
            bootstrap = new Bootstrap();

            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new ReconnectNettyClientHandler(ReconnectNettyClient.this));
                        }
                    });
        } catch (Exception e) {
            log.error(" ReconnectNettyClient error : {}",e);
        } finally {

        }
    }


    public void connect() throws Exception{
        log.info(" netty client start .... ");
        ChannelFuture cf = bootstrap.connect(host, port);
        cf.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if (!channelFuture.isSuccess()) {
                    channelFuture.channel().eventLoop().schedule(() -> {
                        log.error(" 重连服务器 .... ");
                        try {
                            connect();
                        } catch (Exception e) {
                            log.error("connect error {} ", e);
                        }
                    }, 3000, TimeUnit.MILLISECONDS);
                }else {
                    log.info(" 服务端连接成功..... ");
                }
            }
        });
        log.info(" =============   {}  ===========", cf.channel().localAddress());
        cf.channel().closeFuture().sync();
    }


}
